package com.tengju.bff.interfaces.covercharge.controller.admin;

import com.idanchuang.component.config.apollo.util.ConfigUtil;
import com.tengju.bff.domain.shared.JsonUtil;
import com.tengju.bff.interfaces.covercharge.constant.CoverChargeErrorCode;
import com.tengju.bff.interfaces.covercharge.constant.HeavyKeyEnum;
import com.tengju.bff.interfaces.covercharge.entity.vo.*;
import com.tengju.bff.interfaces.covercharge.service.ISmsConfirmationService;
import com.tengju.bff.interfaces.covercharge.util.redis.HeavyUtil;
import com.tengju.bff.interfaces.shared.ApiResponse;
import com.tengju.bff.interfaces.shared.servlet.ManageEntrance;
import com.tengju.payment.application.transfer.TransferService;
import com.tengju.payment.domain.model.transfer.UnionMerchantBalanceQueryRequest;
import com.tengju.payment.domain.model.transfer.UnionMerchantBalanceQueryResponse;
import com.tengju.payment.domain.shard.DoubleCalculator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;

@RestController
@Slf4j
@RequestMapping("/manage/playWithConfirmation")
@Api(value = "playWithConfirmation", tags = "打款确认")
@ManageEntrance
public class PlayWithConfirmationController {

    @Autowired
    private PersonalGiveController personalGiveController;

    @Autowired
    private AdminApplyRecordController adminApplyRecordController;

    @Resource
    private ISmsConfirmationService smsConfirmationService;

    @Autowired
    private TransferService transferService;


    @PostMapping("/playWithConfirmation")
    @ResponseBody
    @ApiOperation(value = "打款确认信息", notes = "打款确认信息")
    @RequiresRoles("sso")
    public ApiResponse<?> playWithConfirmation(@RequestBody PlayWithConfirmationVo req) {
        PlayWithConfirmationPreviewVo playWithConfirmationPreviewVo = new PlayWithConfirmationPreviewVo();
        UnionMerchantBalanceQueryRequest merchantAmountRequest = new UnionMerchantBalanceQueryRequest();
        switch (req.getType()) {
            case "1":
                if (CollectionUtils.isEmpty(req.getCycleAddIds())) {
                    return ApiResponse.newFailure(CoverChargeErrorCode.PARAM_ERROR.getCode(), "请选择需要打款的记录！");
                }
                playWithConfirmationPreviewVo = smsConfirmationService.playWithConfirmationWithBatchNotSinceCertification(req);
                merchantAmountRequest.setCertificationType(0);
                break;
            case "2":
                String date = req.getDate();
                if (StringUtils.isBlank(date)) {
                    return ApiResponse.newFailure(CoverChargeErrorCode.PARAM_ERROR.getCode(), "请选择周期时间！");
                }
                playWithConfirmationPreviewVo = smsConfirmationService.playWithConfirmationWithAllNotSinceCertificationPage(req);
                merchantAmountRequest.setCertificationType(0);
                break;
            case "3":
                if (CollectionUtils.isEmpty(req.getCycleAddIds())) {
                    return ApiResponse.newFailure(CoverChargeErrorCode.PARAM_ERROR.getCode(), "请选择需要打款的记录！");
                }
                playWithConfirmationPreviewVo = smsConfirmationService.playWithConfirmationWithBatchSinceCertification(req);
                merchantAmountRequest.setCertificationType(1);
                break;
            case "4":
                playWithConfirmationPreviewVo = smsConfirmationService.playWithConfirmationWithAllSinceCertification(req);
                merchantAmountRequest.setCertificationType(1);
                break;
            default:

        }
        UnionMerchantBalanceQueryResponse result = transferService.merchantBalanceQuery(merchantAmountRequest);
        log.info("merchantAmountResponse{}", JsonUtil.toJSONString(result));
        playWithConfirmationPreviewVo.setDtChannelAccountBalance(
                BigDecimal.valueOf(DoubleCalculator.divide(result.getUseAmt().getValue(), 100, RoundingMode.HALF_UP)));
        return ApiResponse.newSuccess(playWithConfirmationPreviewVo);
    }

    @GetMapping("/accessToVerifyPhoneNumber")
    @ResponseBody
    @ApiOperation(value = "获取打款确认手机验证的手机号", notes = "获取打款确认手机验证的手机号")
    public ApiResponse<?> accessToVerifyPhoneNumber(@RequestParam(defaultValue = "") String approvers) {
        if (StringUtils.isBlank(approvers)) {
            return ApiResponse.newFailure(CoverChargeErrorCode.PARAM_ERROR.getCode(), "申请人不能为空");
        }
        String[] cycleDay = ConfigUtil.getConfig().getStringArray("withdrawal.confirmation.phone", "");
        return ApiResponse.newSuccess(cycleDay);
    }

    @PostMapping("/notSinceCertificationBatchSms")
    @ApiOperation(value = "发送短信验证", notes = "发送验证短信")
    public ApiResponse<?> notSinceCertificationSms(@RequestBody PlayWithConfirmationSendSmsVo req) {
        if (StringUtils.isBlank(req.getApprovers())) {
            return ApiResponse.newFailure(CoverChargeErrorCode.PARAM_ERROR.getCode(), "申请人不能为空");
        }

        if (StringUtils.isBlank(req.getPhone())) {
            return ApiResponse.newFailure(CoverChargeErrorCode.PARAM_ERROR.getCode(), "手机号不能不选");
        }
        String[] cycleDay = ConfigUtil.getConfig().getStringArray("withdrawal.confirmation.phone", "");
        Boolean isPhone = false;
        for (String cycle : cycleDay) {
            if (cycle.equals(req.getPhone())) {
                isPhone = true;
                break;
            }
        }
        if (!isPhone) {
            return ApiResponse.newFailure(CoverChargeErrorCode.PARAM_ERROR.getCode(), "手机号选择错误");
        }

        if (HeavyUtil.isRun(req.getType() + HeavyKeyEnum.PAID_CONFIRM_HEAVY.getCode() + req.getApprovers())) {
            return ApiResponse.newFailure(CoverChargeErrorCode.PARAM_ERROR.getCode(), "请勿快速点击");
        }
        String sendResult = null;
        try {
            sendResult = smsConfirmationService.send(req.getType(), req.getApprovers(), req.getPhone(), req.getApproversName());
        } catch (Exception e) {
            log.error("获取验证码失败", e);
            return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), "系统错误");
        } finally {
            HeavyUtil.runDone(req.getType() + HeavyKeyEnum.PAID_CONFIRM_HEAVY.getCode() + req.getApprovers());
        }
        if ("".equals(sendResult)) {
            return ApiResponse.newSuccess("发送验证码成功");
        } else {
            return ApiResponse.newFailure(CoverChargeErrorCode.BUSINESS_ERROR.getCode(), sendResult);
        }
    }

    @PostMapping("/validationCode")
    @ApiOperation(value = "短信验证", notes = "验证短信")
    public ApiResponse<?> validationCode(@RequestBody PlayWithConfirmationSendSmsVo req) {
        if (StringUtils.isBlank(req.getApprovers())) {
            return ApiResponse.newFailure(CoverChargeErrorCode.PARAM_ERROR.getCode(), "申请人不能为空");
        }

        if (StringUtils.isBlank(req.getPhone())) {
            return ApiResponse.newFailure(CoverChargeErrorCode.PARAM_ERROR.getCode(), "手机号不能不选");
        }
        String[] cycleDay = ConfigUtil.getConfig().getStringArray("withdrawal.confirmation.phone", "");
        Boolean isPhone = false;
        for (String cycle : cycleDay) {
            if (cycle.equals(req.getPhone())) {
                isPhone = true;
                break;
            }
        }
        if (!isPhone) {
            return ApiResponse.newFailure(CoverChargeErrorCode.PARAM_ERROR.getCode(), "手机号选择错误");
        }

        if ("".equals(req.getCode())) {
            return ApiResponse.newFailure(CoverChargeErrorCode.PARAM_ERROR.getCode(), "验证码不能为空");
        }
        if (HeavyUtil.isRun(req.getType() + HeavyKeyEnum.PAID_CONFIRM_HEAVY.getCode() + req.getApprovers())) {
            return ApiResponse.newFailure(CoverChargeErrorCode.PARAM_ERROR.getCode(), "请勿快速点击");
        }
        String sendResult = null;
        try {
            sendResult = smsConfirmationService.validation(req.getType(), req.getApprovers(), req.getCode());
        } catch (Exception e) {
            log.error("验证码验证失败", e);
            return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), "系统错误");
        } finally {
            HeavyUtil.runDone(req.getType() + HeavyKeyEnum.PAID_CONFIRM_HEAVY.getCode() + req.getApprovers());
        }
        //TODO 测试二期时候删除下面一行
        //sendResult = "";

        AdminPersonalGiveOnlinePayQueryVo reqApply = null;
        AdminSinceCertificationBatchMoneyVo selfReqApply = null;
        ApiResponse result = null;
        if ("".equals(sendResult)) {
            // 验证码正确后进行提现操作
            try {
                switch (req.getType()) {
                    case "1":
                        reqApply = new AdminPersonalGiveOnlinePayQueryVo();
                        reqApply.setApprovers(req.getApprovers());
                        reqApply.setCycleAddIds(req.getCycleAddIds());
                        reqApply.setDate(req.getDate());
                        result = personalGiveController.batchOnlinePayMoney(reqApply);
                        break;
                    case "2":
                        reqApply = new AdminPersonalGiveOnlinePayQueryVo();
                        reqApply.setApprovers(req.getApprovers());
                        reqApply.setCycleAddIds(req.getCycleAddIds());
                        reqApply.setDate(req.getDate());
                        result = personalGiveController.allOnlinePayMoney(reqApply);
                        break;
                    case "3":
                        // 自认证批量打款
                        selfReqApply = new AdminSinceCertificationBatchMoneyVo();
                        selfReqApply.setApprovers(req.getApprovers());
                        selfReqApply.setCycleAddIds(req.getCycleAddIds());
                        result = adminApplyRecordController.batchProcessingWithdrawalRecord(selfReqApply);
                        break;
                    case "4":
                        // 自认证全量打款
                        selfReqApply = new AdminSinceCertificationBatchMoneyVo();
                        selfReqApply.setApprovers(req.getApprovers());
                        selfReqApply.setCycleAddIds(req.getCycleAddIds());
                        result = adminApplyRecordController.allProcessingWithdrawalRecord(selfReqApply);
                        break;
                    default:

                }
            } catch (Exception e) {
                log.error("打款验证后出现系统错误:请求信息:{},错误信息:{}", req, e);
                return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), "系统错误");
            }
            if (result.isSuccess()) {
                smsConfirmationService.validationDone(req.getType(), req.getApprovers(), req.getCode());
            }

            return result;
        } else {
            return ApiResponse.newFailure(CoverChargeErrorCode.BUSINESS_ERROR.getCode(), sendResult);
        }


    }


}
